﻿using System.Text;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.JScriptEngine;
using RAP.Framework.Libary.DomTemplateBuilder.Element;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler
{
	/// <summary>
	/// 脚本Handler
	/// </summary>
	public class ScriptHandler : HandlerBase
	{
		public new Script Element
		{
			get
			{
				return base.Element as Script;
			}
			set
			{
				base.Element = value;
			}
		}

		public override void DoRender ( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var paramObject = GetParamObject ( rootParamObject, parentParamObject, context );
			var scriptContent = string.Empty;
			if ( Element.Src.IsNullOrEmpty ( ) )
			{
				var script = new StringBuilder ( );
				base.DoRender ( script, rootParamObject, parentParamObject, context );
				scriptContent = script.ToString ( ).Trim ( );
			}
			else
			{
				scriptContent = Element.ScriptContent;
			}
			if ( !scriptContent.IsNullOrEmpty ( ) )
			{
				var engine = new JSEngine( );
				engine.SetParameter ( "response", writer );
				engine.SetParameter ( "param", rootParamObject );
				engine.SetParameter ( "parent", parentParamObject );
				engine.SetParameter ( "context", context );
				engine.Run ( scriptContent );
			}
		}
	}
}
